package com.xbts.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.core.exception.ExceptionUtil;
import com.xbts.common.core.utils.StringUtils;
import com.xbts.common.security.utils.SecurityUtils;
import com.xbts.system.domain.SysThirdSysPath;
import com.xbts.system.service.ISysThirdSysPathService;
import org.springframework.stereotype.Service;
import com.xbts.system.mapper.SysThirdBindMapper;
import com.xbts.system.domain.SysThirdBind;
import com.xbts.system.service.ISysThirdBindService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 第三方公司用户账号信息绑定Service业务层处理
 * 
 * @author xbts
 * @date 2023-12-22
 */
@Service
public class SysThirdBindServiceImpl extends ServiceImpl<SysThirdBindMapper, SysThirdBind> implements ISysThirdBindService {

    @Resource
    private ISysThirdSysPathService sysThirdSysPathService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean bind(SysThirdBind sysThirdBind) {
        SysThirdSysPath thirdSysPath = sysThirdSysPathService.getById(sysThirdBind.getThirdSystemId());
        ExceptionUtil.throwsCheckedException(thirdSysPath == null, "第三方系统不存在");

        // 查询是否已经绑定
        SysThirdBind bind = getOne(Wrappers.<SysThirdBind>lambdaQuery()
                .eq(SysThirdBind::getThirdSystemId, sysThirdBind.getThirdSystemId())
                .eq(SysThirdBind::getUserId, SecurityUtils.getUserId()));
        ExceptionUtil.throwsCheckedException(bind != null, "该用户已经绑定过该系统");

        Long userId = SecurityUtils.getUserId();
        sysThirdBind.setUserId(userId);
        return save(sysThirdBind);
    }

    @Override
    public Boolean unbind(String id) {
        return removeById(id);
    }

    @Override
    public void getFullPath(String id, HttpServletResponse response) {
        Long userId = SecurityUtils.getUserId();
        // 获取第三方系统账号密码
        SysThirdBind thirdBind = lambdaQuery().eq(SysThirdBind::getUserId, userId).eq(SysThirdBind::getThirdSystemId, id).one();

        ExceptionUtil.throwsCheckedException(thirdBind == null, "当前用户未绑定第三方系统");

        SysThirdSysPath thirdSysPath = sysThirdSysPathService.getById(id);
        if (thirdSysPath != null) {
            String systemUrl = thirdSysPath.getSystemUrl();
            if (systemUrl.endsWith("/")){
                systemUrl = systemUrl.substring(0, systemUrl.length() - 1);
            }
            // 组装用户账号参数
            if (StringUtils.isNotBlank(thirdSysPath.getUsernameField()) && StringUtils.isNotEmpty(thirdBind.getUsername())){
                systemUrl += "?" + thirdSysPath.getUsernameField()+ "=" + thirdBind.getUsername();
            }
            if (StringUtils.isNotBlank(thirdSysPath.getPasswordField()) && StringUtils.isNotEmpty(thirdBind.getPassword())){
                systemUrl += "&" + thirdSysPath.getPasswordField() + "=" + thirdBind.getPassword();
            }
            try {
                response.sendRedirect(systemUrl);
            } catch (IOException e) {
                log.error("重定向到第三方系统失败", e);
            }
        }
    }

    @Override
    public List<SysThirdBind> detail() {
        Long userId = SecurityUtils.getUserId();
        return list(Wrappers.<SysThirdBind>lambdaQuery().eq(SysThirdBind::getUserId, userId));
    }
}
